package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.DailyTask;
import com.scuec.groupfive.entity.TaskQuestion;
import com.scuec.groupfive.mapper.DailyTaskMapper_eight;
import com.scuec.groupfive.mapper.TaskQuestionMapper;
import com.scuec.groupfive.service.DailyTaskService_eight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Date;

@Service
public class DailyTaskServiceImpl_eight implements DailyTaskService_eight {

    private static final Logger logger = LoggerFactory.getLogger(DailyTaskServiceImpl_eight.class);

    @Autowired
    private DailyTaskMapper_eight dailyTaskMapper;

    @Autowired
    private TaskQuestionMapper taskQuestionMapper;

    private static final Map<String, String> STATUS_MAP = new HashMap<>();
    private static final Map<String, String> REVERSE_STATUS_MAP = new HashMap<>();
    static {
        // 中文到英文的映射
        STATUS_MAP.put("未完成", "pending");
        STATUS_MAP.put("已完成", "completed");
        STATUS_MAP.put("已跳过", "skipped");

        // 英文到英文的映射（保持不变）
        STATUS_MAP.put("pending", "pending");
        STATUS_MAP.put("completed", "completed");
        STATUS_MAP.put("skipped", "skipped");

        // 英文到中文的映射
        REVERSE_STATUS_MAP.put("pending", "未完成");
        REVERSE_STATUS_MAP.put("completed", "已完成");
        REVERSE_STATUS_MAP.put("skipped", "已跳过");
    }

    private DailyTask convertStatusToChinese(DailyTask task) {
        if (task != null && task.getStatus() != null) {
            String chineseStatus = REVERSE_STATUS_MAP.get(task.getStatus());
            if (chineseStatus != null) {
                task.setStatus(chineseStatus);
            }
        }
        return task;
    }

    @Override
    public List<DailyTask> getListTasks() {
        return dailyTaskMapper.getListTasks().stream()
                .map(this::convertStatusToChinese)
                .collect(Collectors.toList());
    }

    @Override
    public int updateTaskStatus(DailyTask dailyTask) {
        String status = STATUS_MAP.get(dailyTask.getStatus());
        if (status == null) {
            throw new IllegalArgumentException("状态值只能是'未完成'、'已完成'或'已跳过'");
        }
        return dailyTaskMapper.updateTaskStatus(
                dailyTask.getTaskId(),
                dailyTask.getUserId(),
                status,
                dailyTask.getContent()
        );
    }

    @Override
    @Transactional
    public int addDailyTask(DailyTask dailyTask) {
        if (dailyTask.getContent() == null || dailyTask.getContent().trim().isEmpty()) {
            throw new IllegalArgumentException("任务内容不能为空");
        }

        logger.info("Service layer received status: {}", dailyTask.getStatus());

        // 强制将status映射为英文
        String mappedStatus = STATUS_MAP.get(dailyTask.getStatus());
        if (mappedStatus == null) {
            mappedStatus = "pending"; // 默认值
            logger.info("Status无效，设置为默认: pending");
        }
        dailyTask.setStatus(mappedStatus);

        // 设置任务日期为当前日期
        if (dailyTask.getTaskDate() == null) {
            dailyTask.setTaskDate(new Date());
            logger.info("Setting task_date to current date: {}", dailyTask.getTaskDate());
        }

        // 获取用户的第一个计划ID
        Long planId = dailyTaskMapper.getFirstPlanIdByUserId(dailyTask.getUserId());
        logger.info("Found plan_id: {} for user_id: {}", planId, dailyTask.getUserId());

        if (planId == null) {
            throw new IllegalArgumentException("用户没有可用的学习计划，请先创建学习计划");
        }
        dailyTask.setPlanId(planId);

        try {
            logger.info("Final task data before insert: {}", dailyTask);
            int result = dailyTaskMapper.addDailyTask(dailyTask);

            // 如果是深度创建且有问题ID和questionsCount，则批量插入task_questions
            if (Boolean.TRUE.equals(dailyTask.getDeep()) && dailyTask.getQuestionId() != null && dailyTask.getQuestionsCount() != null) {
                addTaskQuestionsBatch(dailyTask.getTaskId(), dailyTask.getQuestionId(), dailyTask.getQuestionsCount());
            } else if (Boolean.TRUE.equals(dailyTask.getDeep()) && dailyTask.getQuestionId() != null) {
                // 兼容老逻辑，questionsCount没传时只插入一条
                TaskQuestion taskQuestion = new TaskQuestion();
                taskQuestion.setTaskId(dailyTask.getTaskId());
                taskQuestion.setQuestionId(dailyTask.getQuestionId());
                taskQuestion.setIsCompleted(false);
                taskQuestionMapper.insert(taskQuestion);
            }

            return result;
        } catch (Exception e) {
            logger.error("Error adding daily task: {}", e.getMessage(), e);
            throw new IllegalArgumentException("添加任务失败：" + e.getMessage());
        }
    }

    @Override
    public void addTaskQuestionsBatch(Long taskId, Long questionId, Integer questionsCount) {
        if (questionsCount == null || questionsCount <= 0) return;
        List<TaskQuestion> taskQuestions = new ArrayList<>();
        for (int i = 0; i < questionsCount; i++) {
            TaskQuestion tq = new TaskQuestion();
            tq.setTaskId(taskId);
            tq.setQuestionId(questionId);
            tq.setIsCompleted(false);
            taskQuestions.add(tq);
        }
        taskQuestionMapper.batchInsert(taskQuestions);
    }

    private boolean isValidStatus(String status) {
        return status != null &&
                (status.equals("pending") ||
                        status.equals("completed") ||
                        status.equals("skipped"));
    }

    @Override
    public int deleteDailyTask(Long taskId, Long userId) {
        return dailyTaskMapper.deleteDailyTask(taskId, userId);
    }

    @Override
    public List<DailyTask> getTasksByUsername(String username) {
        return dailyTaskMapper.getTasksByUsername(username).stream()
                .map(this::convertStatusToChinese)
                .collect(Collectors.toList());
    }

    @Override
    public List<DailyTask> getTasksByUsernameAndDate(String username, String date) {
        List<DailyTask> tasks;
        if (date == null || date.isEmpty()) {
            // 获取当天日期字符串 yyyy-MM-dd
            java.time.LocalDate today = java.time.LocalDate.now();
            date = today.toString();
        }
        tasks = dailyTaskMapper.getTasksByUsernameAndDate(username, date);
        return tasks.stream().map(this::convertStatusToChinese).collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getTaskStatisticsByUsername(String username) {
        return dailyTaskMapper.getTaskStatisticsByUsername(username);
    }
}